/*
 * RoboEye - Web client for www.newocr.com that allows you
 * to recognize an image captured by the camera.
 *
 * Copyright (C) Oxygen Development, 2011
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package com.devoxy.roboeye.core.provider;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import com.devoxy.roboeye.global.ContextHolder;

/**
 * Created by Oxygen Development.
 * Author: Dmitriy Tarasov (dm.vl.tarasov@gmail.com)
 * Date: 24.06.11
 * Time: 21:42
 */
public class EntityManager {

    private static final ContentResolver CONTENT_RESOLVER;

    static {
        CONTENT_RESOLVER = ContextHolder.getInstance().getContext().getContentResolver();
    }

    // CRUD operations for Task

    public static long createTask(Task task) {
        ContentValues cv = getValuesFromTask(task);
        Uri uri = CONTENT_RESOLVER.insert(Task.CONTENT_URI, cv);
        return ContentUris.parseId(uri);
    }

    public static Task readTask(String orderBy, String selection, String... selectionArgs) {
        Cursor c = null;
        try {
            c = CONTENT_RESOLVER.query(Task.CONTENT_URI,
                    null,
                    selection,
                    selectionArgs,
                    orderBy);
            if (c.moveToFirst()) {
                return getTaskFromCursor(c);
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return null;
    }

    public static void updateTask(Task task) {
        ContentValues cv = getValuesFromTask(task);
        CONTENT_RESOLVER.update(Task.CONTENT_URI, cv, Task._ID + "=?", new String[] {String.valueOf(task.getId())});
    }

    public static void deleteTask(Task task) {
        CONTENT_RESOLVER.delete(task.getUri(), null, null);
    }

    /**
     * Get youngest task from task-list
     *
     * @return {@link Task} instance or null if error occurred or tasks doesn't exists
     */
    public static Task getFirstTask() {
        return readTask(Task.CREATE_TS + " DESC", Task.FINISHED + " = 0 OR " + Task.FINISHED + " IS NULL");
    }

    public static void markTaskAsStarted(Task task) {
        task.setStarted(true);
        updateTask(task);
    }

    public static void markTaskAsNotStarted(Task task) {
        task.setStarted(false);
        updateTask(task);
    }

    public static void markTaskAsFinished(Task task) {
        task.setFinished(true);
        updateTask(task);
    }

    public static void clearFinishedTasks() {
        CONTENT_RESOLVER.delete(Task.CONTENT_URI, Task.FINISHED + "=1", null);
    }

    public static void cancelAllTasks() {
        CONTENT_RESOLVER.delete(Task.CONTENT_URI, Task.STARTED + "=0 OR " + Task.STARTED + " IS NULL", null);
    }


    private static Task getTaskFromCursor(Cursor c) {
        Task task = new Task();
        task.setId(c.getLong(c.getColumnIndex(Task._ID)));
        task.setCreateTs(c.getLong(c.getColumnIndex(Task.CREATE_TS)));
        task.setSource(c.getString(c.getColumnIndex(Task.SOURCE)));
        task.setTarget(c.getString(c.getColumnIndex(Task.TARGET)));
        task.setType(c.getInt(c.getColumnIndex(Task.TYPE)) == 1);
        task.setStarted(c.getInt(c.getColumnIndex(Task.STARTED)) == 1);
        task.setFinished(c.getInt(c.getColumnIndex(Task.FINISHED)) == 1);
        task.setLanguage(c.getString(c.getColumnIndex(Task.LANGUAGE)));
        task.setRotation(c.getString(c.getColumnIndex(Task.ROTATION)));
        return task;
    }

    private static ContentValues getValuesFromTask(Task task) {
        ContentValues cv = new ContentValues();
        cv.put(Task.SOURCE, task.getSource());
        cv.put(Task.TARGET, task.getTarget());
        cv.put(Task.TYPE, task.getType());
        cv.put(Task.STARTED, task.getStarted());
        cv.put(Task.FINISHED, task.getFinished());
        cv.put(Task.LANGUAGE, task.getLanguage());
        cv.put(Task.ROTATION, task.getRotation());
        return cv;
    }

}
